package com.ev.common.jobs;

import com.ev.framework.utils.OSinfo;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

@Slf4j
@Component
public class BackupsDBJob implements Job {
    @Autowired
    private Environment env;
    /**
     * 若参数变量名修改 QuartzJobController中也需对应修改
     */
    private String parameter;

    public void setParameter(String parameter) {
        this.parameter = parameter;
    }

    @Override
    public void execute(JobExecutionContext context){
        backUpDB(env);
    }

    public static boolean backUpDB(Environment env){
        boolean isSuccess = true;
        boolean linux = OSinfo.isLinux();
        boolean isWindows = OSinfo.isWindows();
        if (linux || isWindows) {
            String filePath = isWindows ? env.getProperty("backups.db.winFilePath") : env.getProperty("backups.db.linuxFilePath");
            String url = env.getProperty("backups.db.dbUrl");
            String dbName = env.getProperty("backups.db.dbName");
            String username = env.getProperty("backups.db.dbUsername");
            String password = env.getProperty("backups.db.dbPassword");
            String port = StringUtils.isEmpty(env.getProperty("backups.db.port"))?"3306":env.getProperty("backups.db.port");
            boolean isDocker = Boolean.parseBoolean(env.getProperty("backups.db.isDocker"));
            String dockerName = env.getProperty("backups.db.dockerName");
            File uploadDir = new File(filePath);
            if (!uploadDir.exists()) {
                isSuccess = uploadDir.mkdirs();
            }
            StringBuilder cmds = new StringBuilder();

            // windows-server
//  MySQL8          --column-statistics=0
            if (isWindows && !isDocker) {
                cmds.append("cmd /c mysqldump")
                        .append(" -u")
                        .append(username)
                        .append(" -p")
                        .append(password)
                        .append(" -h")
                        .append(url)
                        .append(" -P")
                        .append(port)
                        .append(" ")
                        .append(dbName)
                        .append(" > ")
                        .append(filePath)
                        .append("\\").append(dbName).append(new java.util.Date().getTime())
                        .append(".sql");
            }


            // Linux
            if (linux && !isDocker) {
                cmds.append("mysqldump")
                        .append(" -u")
                        .append(username)
                        .append(" -p")
                        .append(password)
                        .append(" -h")
                        .append(url)
                        .append(" -P")
                        .append(port)
                        .append(" ")
                        .append(dbName)
                        .append(" -r ")
                        .append(filePath)
                        .append("/")
                        .append(dbName)
                        .append(new java.util.Date().getTime())
                        .append(".sql");
            }

            // docker 环境
            if (isDocker) {
                cmds.append("sh ").append(filePath).append("/").append("dbback.sh");
//                cmds.append("docker exec -i ")
//                        .append(dockerName)
//                        .append(" mysqldump -t")
//                        .append(" -u")
//                        .append(username)
//                        .append(" -p")
//                        .append(password)
////                        .append(" -h")
////                        .append(url)
//                        .append(" ")
//                        .append(dbName)
//                        .append(" -e>")
//                        .append("\""+filePath)
//                        .append("/")
//                        .append(dbName)
//                        .append(new java.util.Date().getTime())
//                        .append(".sql\"");
            }

            try {
                log.info("执行命令:" + cmds.toString());
                Process process = Runtime.getRuntime().exec(cmds.toString());
                if (process.waitFor() == 0) {// 0 。
                    log.info("线程正常终止");
                }else {
                    isSuccess = false;
                    log.error("命令执行失败");
                }
                process.getOutputStream().close();
                @Cleanup BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "gbk"));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                log.info(sb.toString());
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        return isSuccess;
    }

}
